package cn.wlinker.video.monitor.utils;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.log.StaticLog;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
 * 构建流的带返回参数的线程池工具类
 * @author gxsjx
 * @version 1.0
 * @date 2022/7/26
 */
public class BuildStreamThreadPoolUtils<T> {

    private final LinkedList<Future<T>> futureList = new LinkedList<>();

    /**
     * 使用线程池并发构建流
     *
     * @param task
     */
    public void submit(Callable<T> task) {
        Future<T> tFuture = ThreadUtil.execAsync(task);
        futureList.add(tFuture);
    }

    /**
     * 获取构建的对象，tFuture.get()是阻塞方法，所以是按顺序返回数据
     *
     * @return
     */
    public List<T> get() {
        List<T> result = new LinkedList<>();
        for (Future<T> tFuture : futureList) {
            try {
                T t = tFuture.get();
                if (t != null) {
                    result.add(tFuture.get());
                }else{
                    result.add(null);
                }
            } catch (Exception e) {
                StaticLog.error(e,"获取对象异常");
                result.add(null);
            }
        }
        return result;
    }
}